package com.practice.blog.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;
import lombok.extern.slf4j.Slf4j;

import java.security.Key;
import java.util.Base64;
import java.util.Date;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: hp
 * Date: 2025-01-30
 * Time: 18:49
 */
@Slf4j
public class JwtUtils {
    private static final String secret = "sRVkEwZgWTj1k1PeyhX5v0UAdXoOR3e6+5debiegssA=";
    private static final Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secret));

    //24小时
    private static final long expiration = 24 * 60 * 1000;

    //生成token
    public static String genToken(Map<String,Object> map) {
        return Jwts.builder()
                .setClaims(map)
                .signWith(key)
                .setExpiration(new Date(System.currentTimeMillis()+expiration))
                .setIssuedAt(new Date())
                .compact();
    }

    //校验token
    public static Claims parseToken(String token) {
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        Claims body = null;
        try {
            body = build.parseClaimsJws(token).getBody();
            return body;
        }catch (ExpiredJwtException e) {
            log.error("token过期,token:{}",token);
        }catch (SignatureException e) {
            log.error("签名不匹配,token:{}",token);
        }catch (Exception e) {
            log.error("token解析失败,token:{}",token);
        }
        return null;
    }
}
